"use client";

import React, { useState, useEffect } from "react";
import {
	Form,
	Input,
	Button,
	Space,
	message,
	Typography,
	Select,
	Collapse,
	Modal,
	Empty
} from "antd";
import type { FormInstance } from 'antd/es/form';
import { PlusOutlined } from "@ant-design/icons";
import { 
	getRecruitmentAnnouncements, 
	updateRecruitmentAnnouncement,
	createDeptPositions,
	deleteDeptPositions,
	ApiResponse,
	UpdateRecruitmentAnnouncementParams,
	CreateDeptPositionsRequest,
	DeleteDeptPositionsRequest,
	AnnouncementPosition
} from '@/lib/recruitment';
import { getAllDepartments as getAllDepartmentsFromDepartments } from '@/lib/departments';
import { getAcademyList as getAcademyListFromAcademy } from '@/lib/academy';
import { getAllOtherDepartments as getAllOtherDepartmentsFromOtherDept } from '@/lib/otherdept';

// 判断当前环境是否为开发环境
const isDevelopment = process.env.NODE_ENV === 'development';

const { Title } = Typography;
const { Panel } = Collapse;

/* 数据接口类型定义 */
export interface PositionData {
	positionNumber: string;
	positionName: string;
	positionProperties: string;
	// 岗位描述由模板回填，用户不可修改
	jobDescription: string;
	jobRequired: string;
	person: number;
	professionalSkillsRight: number;
	communicationSkillsRight: number;
	teamworkAbilityRight: number;
	// 更新接口可选字段
	content?: string;
}

export interface DeptData {
	// 页面上用人部门的编号（提交时转换为 numbering）
	numbering: string;
	name?: string;
	positions: PositionData[];
}

// 明确定义组件属性类型接口
export interface DeptManagePageProps {
	selectedPlanId: string;
	onCancel?: () => void;
	onSuccess?: () => void;
}

// 部门管理内容组件
const DeptManageContent: React.FC<DeptManagePageProps> = ({ selectedPlanId, onCancel, onSuccess }) => {
	// 招聘公告数据（包含 planId 与 planType）
	const [announcement, setAnnouncement] = useState<any>(null);
	// 招聘计划类型，本示例只处理 planType === 1
	const [planType, setPlanType] = useState<number>(1);
	// 用人部门及其岗位
	const [depts, setDepts] = useState<DeptData[]>([]);
	// 部门下拉选项（用于新增用人部门和岗位）
	const [deptOptions, setDeptOptions] = useState<any[]>([]);

	// ============== 更新岗位相关状态 ==============
	const [updateModalVisible, setUpdateModalVisible] = useState(false);
	const [updateForm] = Form.useForm();
	// 记录当前编辑的部门和岗位索引
	const [updateDeptIndex, setUpdateDeptIndex] = useState<number | null>(null);
	const [updatePosIndex, setUpdatePosIndex] = useState<number | null>(null);

	// ============== 新增岗位（已有部门下）相关状态 ==============
	const [addModalVisible, setAddModalVisible] = useState(false);
	const [addForm] = Form.useForm();
	// 当前在哪个部门下新增岗位
	const [addDeptIndex, setAddDeptIndex] = useState<number | null>(null);

	// ============== 新增用人部门和岗位（当页面无部门时） ==============
	const [deptAddModalVisible, setDeptAddModalVisible] = useState(false);
	const [deptAddForm] = Form.useForm();

	// 添加一个状态来控制岗位选择的重新渲染
	const [selectedDepartment, setSelectedDepartment] = useState<string | null>(null);

	// 添加部门数据加载完成标志
	const [deptDataLoaded, setDeptDataLoaded] = useState(false);

	// 添加状态来跟踪展开的面板
	const [activeKeys, setActiveKeys] = useState<string[]>([]);

	// 修改返回部门名称的函数，增加安全检查
	const getDepartmentName = (deptNumber: string) => {
		// 如果参数无效，返回默认文本
		if (deptNumber === undefined || deptNumber === null) {
			console.error('[getDepartmentName] 部门编号参数无效:', deptNumber);
			return '未知部门';
		}
		
		console.log('[getDepartmentName] 正在查找部门名称, 部门编号:', deptNumber);
		console.log('[getDepartmentName] 当前计划类型:', planType);
		console.log('[getDepartmentName] 部门数据是否加载完成:', deptDataLoaded);
		console.log('[getDepartmentName] 可用的部门选项数量:', deptOptions.length);
		
		if (!deptNumber) {
			console.log('[getDepartmentName] 部门编号为空，返回未知部门');
			return '未知部门 (编号未提供)';
		}
		
		if (!deptDataLoaded || deptOptions.length === 0) {
			console.log('[getDepartmentName] 部门数据未加载完成或为空，返回未知部门');
			return `未知部门 (编号:${deptNumber})`;
		}

		// 根据部门编号查找对应的部门
		const department = deptOptions.find(dept => dept.number === deptNumber);
		console.log('[getDepartmentName] 找到的部门:', department);
		
		if (department) {
			let deptTypeText = '';
			if (planType === 1) {
				deptTypeText = '职能部门';
			} else if (planType === 2) {
				deptTypeText = '二级学院';
			} else if (planType === 3) {
				deptTypeText = '其他部门';
			}
			
			const name = `${department.name}（${deptTypeText}，编号：${department.number}）`;
			console.log('[getDepartmentName] 返回的部门名称:', name);
			return name;
		}

		console.log('[getDepartmentName] 未找到匹配部门，返回未知部门');
		return `未知部门 (编号:${deptNumber})`;
	};

	// 模拟岗位模板数据（实际可通过接口获取）
	const jobTemplates: Record<string, any> = {
		D1: {
			positionNumber: "111",
			positionName: "类造完众",
			positionProperties: "aute dolor eiusmod ex",
			jobDescription: "anim do"
		},
		D2: {
			positionNumber: "222",
			positionName: "示例岗位",
			positionProperties: "示例性质",
			jobDescription: "示例描述"
		}
	};

	// 添加一个函数，确保部门数据已加载
	const ensureDeptDataLoaded = async () => {
		if (!deptDataLoaded || deptOptions.length === 0) {
			console.log('部门数据未加载，正在加载...');
			if (planType > 0) {
				// 只有在计划类型有效时才加载部门数据
				await fetchDepartmentsByType(planType);
			} else {
				console.error('计划类型无效，无法加载部门数据');
			}
		} else {
			console.log('部门数据已加载，部门数量:', deptOptions.length);
		}
	};

	// 修改fetchData函数，确保在数据加载前重置所有状态
	const fetchData = async () => {
		try {
			console.log("开始获取招聘计划数据, planId:", selectedPlanId);
			// 先重置所有状态，防止数据混淆
			setAnnouncement(null);
			setPlanType(0); // 先将计划类型重置为0(无效值)
			setDepts([]);
			setDeptOptions([]);
			setDeptDataLoaded(false);
			
			// 重置模态框相关状态
			setAddDeptIndex(null);
			setUpdateDeptIndex(null);
			setUpdatePosIndex(null);
			setSelectedDepartment(null);
			
			const response = await getRecruitmentAnnouncements();
			if (response && response.code === 1) {
				const currentPlan = response.data.find(
					(plan: any) => plan.planId === parseInt(selectedPlanId)
				);
				
				if (currentPlan) {
					console.log("找到对应计划:", currentPlan);
					setAnnouncement(currentPlan);
					const currentPlanType = currentPlan.planType;
					console.log("设置计划类型:", currentPlanType);
					setPlanType(currentPlanType);
					setDepts(currentPlan.depts || []);
					
					// 在设置计划类型后直接获取对应类型的部门数据
					// 这里不用等待状态更新，直接传入currentPlanType
					console.log("根据计划类型获取部门数据:", currentPlanType);
					await fetchDepartmentsByType(currentPlanType);

					// 如果activeKeys为空，则默认展开所有面板
					if (activeKeys.length === 0 && currentPlan.depts && currentPlan.depts.length > 0) {
						const newActiveKeys = currentPlan.depts
							.filter(dept => dept && dept.numbering)
							.map(dept => dept.numbering);
						setActiveKeys(newActiveKeys);
					}
				} else {
					message.error("未找到对应的招聘计划");
				}
			} else {
				message.error(response?.message || "获取数据失败");
			}
		} catch (error) {
			console.error("获取数据失败:", error);
			message.error("获取数据失败");
		}
	};
	
	// 新增函数：根据计划类型获取对应的部门数据
	const fetchDepartmentsByType = async (planTypeValue: number) => {
		// 这里是fetchDepartmentsByType函数的实现
		// 实现与page.tsx中相同
		console.log("按指定类型获取部门数据:", planTypeValue);
		try {
			setDeptDataLoaded(false);
			setDeptOptions([]);
			
			// 根据指定的计划类型获取部门数据
			if (planTypeValue === 1) { // 管理岗位 - 获取职能部门
				try {
					// 调用职能部门API
					console.log("获取职能部门数据，调用/department接口");
					const response = await getAllDepartmentsFromDepartments();
					console.log("获取到的职能部门原始数据:", response);
					
					if (response.data && response.data.code === 1) {
						if (!Array.isArray(response.data.data)) {
							console.error("职能部门数据格式错误，不是数组:", response.data.data);
							setDeptOptions([]);
							setDeptDataLoaded(true);
							return;
						}
						
						// 修正职能部门字段映射
						const depts = response.data.data.map((dept: any) => ({
							number: dept.deptNumber,
							name: dept.deptName,
							id: dept.deptId.toString(),
							positions: dept.positions || []
						}));
						console.log("处理后的职能部门数据:", depts);
						setDeptOptions(depts);
					} else {
						console.error("获取职能部门失败:", response.data);
						setDeptOptions([]);
					}
				} catch (error) {
					console.error("获取职能部门出错:", error);
					setDeptOptions([]);
				}
			} else if (planTypeValue === 2) { // 专任教师 - 获取二级学院
				try {
					// 调用学院API
					console.log("获取二级学院数据，调用/department/academy接口");
					const response = await getAcademyListFromAcademy();
					console.log("获取到的学院原始数据:", response);
					
					// 学院API响应结构不同，直接返回数组
					if (Array.isArray(response)) {
						console.log("学院数据是数组，包含", response.length, "个学院");
						// 映射学院字段
						const academyOptions = response.map((academy: any) => ({
							number: academy.academyNumber,
							name: academy.academyName,
							id: academy.academyId.toString(),
							positions: academy.positions || []
						}));
						console.log("处理后的二级学院数据:", academyOptions);
						setDeptOptions(academyOptions);
					} else {
						console.error("获取学院数据格式不正确:", response);
						setDeptOptions([]);
					}
				} catch (error) {
					console.error("获取学院数据出错:", error);
					setDeptOptions([]);
				}
			} else if (planTypeValue === 3) { // 其他岗位 - 获取其他部门
				try {
					// 调用其他部门API
					console.log("获取其他部门数据，调用/department/otherDept接口");
					const response = await getAllOtherDepartmentsFromOtherDept();
					console.log("获取到的其他部门原始数据:", response);
					
					if (response.data && response.data.code === 1) {
						if (!Array.isArray(response.data.data)) {
							console.error("其他部门数据格式错误，不是数组:", response.data.data);
							setDeptOptions([]);
							setDeptDataLoaded(true);
							return;
						}
						
						const otherDepts = response.data.data.map((dept: any) => ({
							number: dept.otherDeptNumber,
							name: dept.otherDeptName,
							id: dept.otherDeptId.toString(),
							positions: dept.positions || []
						}));
						console.log("处理后的其他部门数据:", otherDepts);
						setDeptOptions(otherDepts);
					} else {
						console.error("获取其他部门失败:", response.data);
						setDeptOptions([]);
					}
				} catch (error) {
					console.error("获取其他部门出错:", error);
					setDeptOptions([]);
				}
			} else {
				console.error("未知的计划类型:", planTypeValue);
				setDeptOptions([]);
			}
			
			setDeptDataLoaded(true);
		} catch (error) {
			console.error("获取部门数据失败:", error);
			message.error("获取部门数据失败");
			setDeptDataLoaded(false);
			setDeptOptions([]);
		}
	};

	// 修改useEffect，确保selectedPlanId变化时重新获取数据
	useEffect(() => {
		if (selectedPlanId) {
			console.log("selectedPlanId变化，重新获取数据:", selectedPlanId);
			fetchData();
		}
	}, [selectedPlanId]);

	// ---------------- 编辑岗位（更新） ----------------
	const showUpdateModal = (deptIdx: number, posIdx: number) => {
		// 安全检查：确保depts和depts[deptIdx]存在
		if (!depts || !depts[deptIdx]) {
			console.error('部门数据不存在:', deptIdx, depts);
			message.error('部门数据不存在，请刷新页面重试');
			return;
		}
		
		// 安全检查：确保部门有numbering属性和positions数组
		if (!depts[deptIdx].numbering || !Array.isArray(depts[deptIdx].positions) || !depts[deptIdx].positions[posIdx]) {
			console.error('部门数据不完整:', depts[deptIdx]);
			message.error('部门数据不完整，请刷新页面重试');
			return;
		}
		
		setUpdateDeptIndex(deptIdx);
		setUpdatePosIndex(posIdx);
		const position = depts[deptIdx].positions[posIdx];
		
		// 安全检查：确保position对象完整
		if (!position) {
			console.error('岗位数据不存在:', posIdx, depts[deptIdx].positions);
			message.error('岗位数据不存在，请刷新页面重试');
			return;
		}
		
		// 设置表单初始数据，岗位描述字段只读
		const formValues: Record<string, any> = {
			numbering: depts[deptIdx].numbering,
			positionName: position.positionName || '',
			jobDescription: position.jobDescription || '',
			jobRequired: position.jobRequired || '',
			person: position.person || 0,
			professionalSkillsRight: position.professionalSkillsRight || 0,
			communicationSkillsRight: position.communicationSkillsRight || 0,
			teamworkAbilityRight: position.teamworkAbilityRight || 0,
		};
		
		// 只有在其他岗位类型时，才设置content字段
		if ((planType as number) === 3) {
			formValues.content = position.content || "";
		}
		
		// 只有在管理岗位类型时，才设置positionProperties字段
		if (planType === 1) {
			formValues.positionProperties = position.positionProperties || '';
		}
		
		updateForm.setFieldsValue(formValues);
		setUpdateModalVisible(true);
	};

	const handleUpdateSubmit = async () => {
		try {
			const values = await updateForm.validateFields();
			if (updateDeptIndex === null || updatePosIndex === null) return;
			const targetDept = depts[updateDeptIndex];
			const targetPosition = targetDept.positions[updatePosIndex];
			
			// 构建基本请求数据
			const requestData: UpdateRecruitmentAnnouncementParams = {
				planId: parseInt(selectedPlanId),
				numbering: targetDept.numbering,
				positionName: targetPosition.positionName,
				jobDescription: targetPosition.jobDescription,
				jobRequired: values.jobRequired,
				person: values.person,
				professionalSkillsRight: values.professionalSkillsRight,
				communicationSkillsRight: values.communicationSkillsRight,
				teamworkAbilityRight: values.teamworkAbilityRight,
			};
			
			// 只有其他岗位类型时，才添加content字段
			if ((planType as number) === 3) {
				requestData.content = values.content;
			}
			
			const response = await updateRecruitmentAnnouncement(requestData);
			
			if (response?.data?.code === 1) {
				message.success("更新成功");
				setUpdateModalVisible(false);
				fetchData();
			} else {
				// 显示具体的错误信息并抛出，让catch捕获
				const errorMsg = typeof response?.data?.data === 'string' 
					? response.data.data 
					: (response?.data?.msg || "更新失败");
				throw new Error(errorMsg);
			}
		} catch (error: any) {
			console.error("更新岗位失败:", error);
			// 尝试提取具体错误信息
			const errorMsg = error.message || "更新失败";
			message.error(errorMsg);
		}
	};

	// ---------------- 渲染部分 ----------------
	// 修改Collapse组件的渲染方式，添加安全检查
	const renderCollapseContent = () => {
		if (!depts || depts.length === 0) {
			return (
				<div style={{ padding: "20px", textAlign: "center" }}>
					<Empty description="暂无用人部门数据" />
				</div>
			);
		}
		
		return (
			<Collapse 
				activeKey={activeKeys}
				onChange={(keys) => setActiveKeys(keys as string[])}
			>
				{depts.map((dept, deptIdx) => {
					// 增加安全检查
					if (!dept || !dept.numbering) {
						console.error(`部门数据不完整，索引: ${deptIdx}`, dept);
						return null;
					}
					
					return (
						<Panel 
							header={`用人部门：${getDepartmentName(dept.numbering)}`}
							key={dept.numbering || `dept-${deptIdx}`}
						>
							{Array.isArray(dept.positions) ? dept.positions.map((pos, posIdx) => (
								<div
									key={`${pos.positionNumber || ''}${pos.positionName || ''}-${posIdx}`}
									style={{
										marginBottom: "10px",
										border: "1px solid #ccc",
										padding: "10px"
									}}
								>
									<div>岗位编号：{pos.positionNumber || '无编号'}</div>
									<div>岗位名称：{pos.positionName || '无名称'}</div>
									{/* 只有管理岗位类型才显示岗位性质 */}
									{planType === 1 && <div>岗位性质：{pos.positionProperties || '无'}</div>}
									<div>岗位描述：{pos.jobDescription || '无描述'}</div>
									<div>任职要求：{pos.jobRequired || '无要求'}</div>
									<div>招聘人数：{pos.person || 0}</div>
									<div>专业技能的权：{pos.professionalSkillsRight || 0}</div>
									<div>沟通能力的权：{pos.communicationSkillsRight || 0}</div>
									<div>团队协作的权：{pos.teamworkAbilityRight || 0}</div>
									{/* 只有其他岗位类型才显示内容字段 */}
									{(planType as number) === 3 && pos.content && (
										<div>内容：{pos.content}</div>
									)}
									<Space style={{ marginTop: "10px" }}>
										<Button
											type="primary"
											onClick={() => showUpdateModal(deptIdx, posIdx)}
										>
											编辑
										</Button>
										<Button danger onClick={() => confirmDeletePosition(deptIdx, posIdx)}>
											删除
										</Button>
									</Space>
								</div>
							)) : (
								<Empty description="暂无岗位数据" />
							)}
							<Button
								type="dashed"
								icon={<PlusOutlined />}
								onClick={() => showAddModal(deptIdx)}
							>
								新增岗位
							</Button>
						</Panel>
					);
				})}
			</Collapse>
		);
	};

	// ---------------- 新增岗位（已有部门下） ----------------
	const showAddModal = (deptIdx: number) => {
		setAddDeptIndex(deptIdx);
		addForm.resetFields();
		
		// 安全检查：确保depts和depts[deptIdx]存在
		if (!depts || !depts[deptIdx]) {
			console.error('部门数据不存在:', deptIdx, depts);
			message.error('部门数据不存在，请刷新页面重试');
			return;
		}
		
		// 安全检查：确保numbering存在
		if (!depts[deptIdx].numbering) {
			console.error('部门编号不存在:', depts[deptIdx]);
			message.error('部门编号不存在，请刷新页面重试');
			return;
		}
		
		// 使用numbering字段而不是deptSelect
		const currentDeptNumber = depts[deptIdx].numbering;
		console.log('新增岗位 - 当前部门编号:', currentDeptNumber);
		console.log('新增岗位 - 当前部门索引:', deptIdx);
		console.log('新增岗位 - 当前部门数据:', depts[deptIdx]);
		console.log('新增岗位 - 当前计划类型:', planType);

		// 先确保获取到最新的部门数据
		if (planType <= 0) {
			console.error('计划类型无效，无法加载部门数据');
			message.error('无法获取部门数据，请刷新页面重试');
			return;
		}

		// 重新获取部门数据，确保数据最新
		fetchDepartmentsByType(planType).then(() => {
			// 查找部门对象并回填部门信息
			const deptObj = deptOptions.find(d => d.number === currentDeptNumber);
			console.log('找到的部门对象:', deptObj);
			
			if (!deptObj) {
				message.warning('未找到对应的部门信息，请刷新页面重试');
				return;
			}
			
			// 回填当前部门编号和名称
			addForm.setFieldsValue({ 
				numbering: currentDeptNumber,
				deptName: getDepartmentName(currentDeptNumber)
			});
			
			// 更新选中的部门状态以更新岗位选择列表
			setSelectedDepartment(currentDeptNumber);
			
			setAddModalVisible(true);
		}).catch(error => {
			console.error('加载部门数据失败:', error);
			message.error('加载部门数据失败，请刷新后重试');
		});
	};

	const handleAddSubmit = async () => {
		try {
			const values = await addForm.validateFields();
			if (addDeptIndex === null) return;
			
			// 构建岗位数据
			const position: AnnouncementPosition = {
				positionNumber: values.positionNumber,
				positionName: values.positionName,
				jobDescription: values.jobDescription,
				jobRequired: values.jobRequired,
				person: values.person,
				professionalSkillsRight: values.professionalSkillsRight,
				communicationSkillsRight: values.communicationSkillsRight,
				teamworkAbilityRight: values.teamworkAbilityRight,
			};
			
			// 只有管理岗位类型才有岗位性质
			if (planType === 1) {
				position.positionProperties = values.positionProperties;
			}
			
			// 构建API请求数据，符合CreateDeptPositionsRequest接口
			const requestData: CreateDeptPositionsRequest = {
				planId: parseInt(selectedPlanId),
				planType: planType,
				depts: [
					{
						numbering: values.numbering,
						positions: [position]
					}
				]
			};
			
			console.log('提交创建岗位的数据:', requestData);
			
			const response = await createDeptPositions(requestData);
			
			if (response && response.code === 1) {
				message.success("添加成功");
				setAddModalVisible(false);
				fetchData();
			} else {
				// 显示具体的错误信息并抛出，让catch捕获
				const errorMsg = typeof response.data === 'string' ? response.data : (response.msg || "添加失败");
				throw new Error(errorMsg);
			}
		} catch (error: any) {
			console.error("添加岗位失败:", error);
			// 尝试提取具体错误信息
			const errorMsg = error.message || "添加失败，请检查表单填写是否完整";
			message.error(errorMsg);
		}
	};

	// ---------------- 删除岗位 ----------------
	const confirmDeletePosition = async (deptIdx: number, posIdx: number) => {
		// 安全检查：确保部门和岗位数据存在
		if (!depts || !depts[deptIdx] || !depts[deptIdx].positions || !depts[deptIdx].positions[posIdx]) {
			console.error('部门或岗位数据不存在:', deptIdx, posIdx, depts);
			message.error('部门或岗位数据不存在，请刷新页面重试');
			return;
		}
		
		const department = depts[deptIdx];
		const position = department.positions[posIdx];
		
		Modal.confirm({
			title: "确认删除",
			content: `确定要删除部门"${getDepartmentName(department.numbering)}"下的岗位"${position.positionName}"吗？`,
			onOk: async () => {
				try {
					// 构建API请求数据，符合DeleteDeptPositionsRequest接口
					const requestData: DeleteDeptPositionsRequest = {
						delPositions: [
							{
								planId: parseInt(selectedPlanId),
								numbering: department.numbering,
								positionName: position.positionName
							}
						]
					};
					
					const response = await deleteDeptPositions(requestData);
					
					if (response && response.code === 1) {
						message.success("删除成功");
						fetchData();
					} else {
						// 显示具体的错误信息并抛出，让catch捕获
						const errorMsg = typeof response.data === 'string' ? response.data : (response.msg || "删除失败");
						throw new Error(errorMsg);
					}
				} catch (error: any) {
					console.error("删除岗位失败:", error);
					// 尝试提取具体错误信息
					const errorMsg = error.message || "删除失败";
					message.error(errorMsg);
				}
			},
			okText: "确认",
			cancelText: "取消"
		});
	};

	// ---------------- 新增用人部门和岗位（页面无部门时） ----------------
	const showDeptAddModal = () => {
		deptAddForm.resetFields();
		// 首先检查计划类型是否有效
		if (planType <= 0) {
			console.error('计划类型无效，无法加载部门数据');
			message.error('无法获取部门数据，请刷新页面重试');
			return;
		}

		// 确保部门数据已加载
		console.log('准备打开新增部门模态框，正在确保部门数据已加载...');
		fetchDepartmentsByType(planType).then(() => {
			if (deptOptions.length === 0) {
				message.warning(`未找到可用的${planType === 1 ? '职能部门' : planType === 2 ? '二级学院' : '其他部门'}数据`);
			}
			setDeptAddModalVisible(true);
		}).catch(error => {
			console.error('加载部门数据失败:', error);
			message.error('加载部门数据失败，请刷新后重试');
		});
	};

	// 修改渲染部门选择的函数
	const renderDeptSelect = () => {
		const planTypeMap = {
			1: { type: '管理岗位', deptType: '职能部门' },
			2: { type: '专任教师', deptType: '二级学院' },
			3: { type: '其他岗位', deptType: '其他部门' }
		};
		
		const planTypeInfo = planTypeMap[planType as keyof typeof planTypeMap] || { type: '未知', deptType: '部门' };

		return (
			<>
				<div style={{ background: '#f6ffed', padding: '10px', border: '1px solid #b7eb8f', borderRadius: '4px', marginBottom: '15px' }}>
					<p style={{ margin: '0', color: '#52c41a' }}>
						<strong>{planTypeInfo.type}招聘计划</strong>只能选择<strong>{planTypeInfo.deptType}</strong>
					</p>
				</div>
				
				<Form.Item 
					label={`选择${planTypeInfo.deptType}`}
					name="numbering" 
					rules={[{ required: true, message: `请选择${planTypeInfo.deptType}` }]}
				>
					<Select 
						placeholder={`请选择${planTypeInfo.deptType}`}
						onChange={(value) => {
							console.log('选择部门时的值:', value);
							console.log('当前所有部门选项:', deptOptions);
							const selectedDept = deptOptions.find(dept => dept.number === value);
							console.log('选中的部门:', selectedDept);
							console.log('该部门下的岗位:', selectedDept?.positions);

							// 清空岗位相关的字段
							deptAddForm.setFieldsValue({
								jobSelect: undefined,
								positionNumber: '',
								positionName: '',
								positionProperties: '',
								jobDescription: ''
							});

							// 更新选中的部门
							setSelectedDepartment(value);
						}}
					>
						{deptOptions.map(dept => (
							<Select.Option key={dept.number} value={dept.number}>
								{dept.name}（编号：{dept.number}）
							</Select.Option>
						))}
					</Select>
				</Form.Item>
			</>
		);
	};

	// 修改岗位选择的处理函数
	const handleJobSelect = (value: string, departmentNumber: string, form: FormInstance) => {
		console.log('=== 岗位选择处理 ===');
		console.log('选中的岗位编号:', value);
		console.log('部门编号:', departmentNumber);
		console.log('当前计划类型:', planType);
		
		// 找到对应的部门
		const department = deptOptions.find(dept => dept.number === departmentNumber);
		console.log('找到的部门:', department);
		
		// 如果未找到部门，无法继续处理
		if (!department) {
			console.error('未找到部门，岗位选择无效');
			return;
		}
		
		// 确保部门有岗位数组
		if (!department.positions || !Array.isArray(department.positions)) {
			console.error('部门不包含岗位数组或格式不正确');
			return;
		}

		// 根据岗位编号查找岗位
		const selectedPosition = department.positions.find(
			(pos: any) => pos.positionNumber === value
		);
		console.log('找到的岗位:', selectedPosition);

		// 如果找到了岗位，设置表单值
		if (selectedPosition) {
			console.log('设置岗位信息到表单:');
			console.log('- 岗位编号:', selectedPosition.positionNumber);
			console.log('- 岗位名称:', selectedPosition.positionName);
			console.log('- 岗位性质:', selectedPosition.positionProperties);
			console.log('- 岗位描述:', selectedPosition.jobDescription);
			
			// 设置表单值
			const formValues = {
				positionNumber: selectedPosition.positionNumber || '',
				positionName: selectedPosition.positionName || '',
				positionProperties: selectedPosition.positionProperties || '',
				jobDescription: selectedPosition.jobDescription || ''
			};
			console.log('最终表单值:', formValues);
			
			form.setFieldsValue(formValues);
		} else {
			console.error('未找到匹配的岗位信息，无法设置表单值');
		}
	};

	const handleDeptAddSubmit = async () => {
		try {
			const values = await deptAddForm.validateFields();
			
			// 构建岗位数据
			const position: AnnouncementPosition = {
				positionNumber: values.positionNumber,
				positionName: values.positionName,
				jobDescription: values.jobDescription,
				jobRequired: values.jobRequired,
				person: values.person,
				professionalSkillsRight: values.professionalSkillsRight,
				communicationSkillsRight: values.communicationSkillsRight,
				teamworkAbilityRight: values.teamworkAbilityRight,
			};
			
			// 只有管理岗位类型才有岗位性质
			if (planType === 1) {
				position.positionProperties = values.positionProperties;
			}
			
			// 构建API请求数据，使用createDeptPositions而不是updateRecruitmentAnnouncement
			const requestData: CreateDeptPositionsRequest = {
				planId: parseInt(selectedPlanId),
				planType: planType,
				depts: [
					{
						numbering: values.numbering,
						positions: [position]
					}
				]
			};
			
			console.log('提交创建用人部门岗位的数据:', requestData);
			
			// 使用正确的API函数：createDeptPositions
			const response = await createDeptPositions(requestData);
			
			if (response && response.code === 1) {
				message.success("添加成功");
				setDeptAddModalVisible(false);
				
				// 确保新添加的部门会被展开
				const newDeptNumber = values.numbering;
				if (newDeptNumber && !activeKeys.includes(newDeptNumber)) {
					setActiveKeys([...activeKeys, newDeptNumber]);
				}
				
				fetchData();
			} else {
				// 显示具体的错误信息并抛出，让catch捕获
				const errorMsg = typeof response.data === 'string' ? response.data : (response.msg || "添加失败");
				throw new Error(errorMsg);
			}
		} catch (error: any) {
			console.error("添加用人部门岗位失败:", error);
			// 尝试提取具体错误信息
			const errorMsg = error.message || "添加失败，请检查表单填写是否完整";
			message.error(errorMsg);
		}
	};

	return (
		<div style={{ padding: "20px" }}>
			<Title level={3}>招聘计划岗位管理 - {selectedPlanId}</Title>
			{/* 如果有用人部门，则显示列表；否则显示添加用人部门和岗位的按钮 */}
			{depts && depts.length > 0 ? (
				renderCollapseContent()
			) : (
				<div>
					{(planType === 1 || planType === 2) && (
						<Button type="dashed" icon={<PlusOutlined />} onClick={showDeptAddModal}>
							添加用人部门和岗位
						</Button>
					)}
				</div>
			)}

			{/* 更新岗位模态框 */}
			<Modal
				title="更新岗位"
				visible={updateModalVisible}
				onCancel={() => setUpdateModalVisible(false)}
				onOk={handleUpdateSubmit}
			>
				<Form form={updateForm} layout="vertical">
					<Form.Item label="用人部门编号" name="numbering">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="岗位名称" name="positionName">
						<Input readOnly />
					</Form.Item>
					{/* 只有管理岗位类型才显示岗位性质 */}
					{planType === 1 && (
						<Form.Item label="岗位性质" name="positionProperties">
							<Input readOnly />
						</Form.Item>
					)}
					<Form.Item label="岗位描述" name="jobDescription">
						<Input.TextArea readOnly />
					</Form.Item>
					<Form.Item label="任职要求" name="jobRequired" rules={[{ required: true, message: "请输入任职要求" }]}>
						<Input.TextArea />
					</Form.Item>
					<Form.Item label="招聘人数" name="person" rules={[{ required: true, message: "请输入招聘人数" }]}>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="专业技能的权"
						name="professionalSkillsRight"
						rules={[{ required: true, message: "请输入专业技能的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="沟通能力的权"
						name="communicationSkillsRight"
						rules={[{ required: true, message: "请输入沟通能力的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="团队协作的权"
						name="teamworkAbilityRight"
						rules={[{ required: true, message: "请输入团队协作的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					{/* 只有其他岗位类型才显示内容字段 */}
					{(planType as number) === 3 && (
						<Form.Item label="内容" name="content">
							<Input />
						</Form.Item>
					)}
				</Form>
			</Modal>
			
			{/* 新增岗位模态框（已有部门下） */}
			<Modal
				title="新增岗位"
				visible={addModalVisible}
				onCancel={() => setAddModalVisible(false)}
				onOk={handleAddSubmit}
			>
				<Form form={addForm} layout="vertical">
					<Form.Item label="用人部门编号" name="numbering">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="用人部门名称" name="deptName">
						<Input readOnly />
					</Form.Item>
					{/* 添加岗位选择 */}
					{addDeptIndex !== null && (
						<Form.Item 
							label="选择岗位" 
							name="jobSelect" 
							rules={[{ required: true, message: "请选择岗位" }]}
						>
							<Select 
								placeholder="请选择岗位"
								onChange={(value) => {
									console.log('岗位选择变化 - 值:', value);
									console.log('岗位选择变化 - 当前部门索引:', addDeptIndex);
									
									if (addDeptIndex !== null) {
										const deptNumber = depts[addDeptIndex].numbering;
										console.log('岗位选择变化 - 部门编号:', deptNumber);
										handleJobSelect(value, deptNumber, addForm);
									}
								}}
							>
								{(() => {
									if (addDeptIndex === null) return [];
									
									const deptNumber = depts[addDeptIndex].numbering;
									console.log('渲染岗位选择 - 部门编号:', deptNumber);
									
									const selectedDept = deptOptions.find(dept => dept.number === deptNumber);
									console.log('渲染岗位选择 - 找到的部门:', selectedDept);
									
									if (!selectedDept?.positions || selectedDept.positions.length === 0) {
										return [
											<Select.Option key="no-positions" value="" disabled>
												该部门下暂无岗位
											</Select.Option>
										];
									}
									
									// 过滤岗位，确保只显示与当前招聘计划类型匹配的岗位
									return selectedDept.positions
										.filter((pos: any) => {
											// 管理岗位招聘计划(planType=1)应该只显示职能部门类型(deptType=1)的岗位
											// 专任教师招聘计划(planType=2)应该只显示二级学院类型(deptType=2)的岗位
											const positionDeptType = pos.deptType || 0;
											const match = (planType === 1 && positionDeptType === 1) || 
												   (planType === 2 && positionDeptType === 2);
											console.log(`检查岗位 ${pos.positionName}(id=${pos.positionId}) - deptType=${positionDeptType}, planType=${planType}, 匹配: ${match}`);
											return match;
										})
										.map((pos: any) => {
											const positionNumber = pos.positionNumber || '';
											const positionName = pos.positionName || '未命名岗位';
											
											return (
												<Select.Option key={positionNumber} value={positionNumber}>
													{positionName}（编号：{positionNumber}）
												</Select.Option>
											);
										});
								})()}
							</Select>
						</Form.Item>
					)}
					<Form.Item label="岗位编号" name="positionNumber">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="岗位名称" name="positionName">
						<Input readOnly />
					</Form.Item>
					{/* 只有管理岗位类型才显示岗位性质 */}
					{planType === 1 && (
						<Form.Item label="岗位性质" name="positionProperties">
							<Input readOnly />
						</Form.Item>
					)}
					<Form.Item label="岗位描述" name="jobDescription">
						<Input.TextArea readOnly />
					</Form.Item>
					<Form.Item label="任职要求" name="jobRequired" rules={[{ required: true, message: "请输入任职要求" }]}>
						<Input.TextArea />
					</Form.Item>
					<Form.Item label="招聘人数" name="person" rules={[{ required: true, message: "请输入招聘人数" }]}>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="专业技能的权"
						name="professionalSkillsRight"
						rules={[{ required: true, message: "请输入专业技能的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="沟通能力的权"
						name="communicationSkillsRight"
						rules={[{ required: true, message: "请输入沟通能力的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="团队协作的权"
						name="teamworkAbilityRight"
						rules={[{ required: true, message: "请输入团队协作的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					{/* 只有其他岗位类型才显示内容字段 */}
					{(planType as number) === 3 && (
						<Form.Item label="内容" name="content">
							<Input />
						</Form.Item>
					)}
				</Form>
			</Modal>
			
			{/* 新增用人部门和岗位模态框（当页面无部门时使用） */}
			{(planType === 1 || planType === 2) && (
				<Modal
					title="新增用人部门和岗位"
					visible={deptAddModalVisible}
					onCancel={() => setDeptAddModalVisible(false)}
					onOk={handleDeptAddSubmit}
				>
					<Form form={deptAddForm} layout="vertical">
						{/* 部门选择 */}
						{renderDeptSelect()}
						
						{/* 岗位选择 */}
						{selectedDepartment && (
							<Form.Item 
								label="选择岗位" 
								name="jobSelect" 
								rules={[{ required: true, message: "请选择岗位" }]}
							>
								<Select 
									placeholder="请选择岗位"
									onChange={(value) => handleJobSelect(value, selectedDepartment, deptAddForm)}
								>
									{(() => {
										// 根据选中的部门筛选岗位
										const selectedDept = deptOptions.find(dept => dept.number === selectedDepartment);
										console.log('渲染岗位选择 - 找到的部门:', selectedDept);
										
										if (!selectedDept?.positions || selectedDept.positions.length === 0) {
											return [
												<Select.Option key="no-positions" value="" disabled>
													该部门下暂无岗位
												</Select.Option>
											];
										}
										
										// 过滤岗位，确保只显示与当前招聘计划类型匹配的岗位
										return selectedDept.positions
											.filter((pos: any) => {
												// 管理岗位招聘计划(planType=1)应该只显示职能部门类型(deptType=1)的岗位
												// 专任教师招聘计划(planType=2)应该只显示二级学院类型(deptType=2)的岗位
												const positionDeptType = pos.deptType || 0;
												const match = (planType === 1 && positionDeptType === 1) || 
													(planType === 2 && positionDeptType === 2);
												console.log(`检查岗位 ${pos.positionName}(id=${pos.positionId}) - deptType=${positionDeptType}, planType=${planType}, 匹配: ${match}`);
												return match;
											})
											.map((pos: any) => {
												const positionNumber = pos.positionNumber || '';
												const positionName = pos.positionName || '未命名岗位';
												
												return (
													<Select.Option key={positionNumber} value={positionNumber}>
														{positionName}（编号：{positionNumber}）
													</Select.Option>
												);
											});
									})()}
								</Select>
							</Form.Item>
						)}
						
						<Form.Item label="岗位编号" name="positionNumber">
							<Input readOnly />
						</Form.Item>
						<Form.Item label="岗位名称" name="positionName">
							<Input readOnly />
						</Form.Item>
						{/* 只有管理岗位类型才显示岗位性质 */}
						{planType === 1 && (
							<Form.Item label="岗位性质" name="positionProperties">
								<Input readOnly />
							</Form.Item>
						)}
						<Form.Item label="岗位描述" name="jobDescription">
							<Input.TextArea readOnly />
						</Form.Item>
						<Form.Item label="任职要求" name="jobRequired" rules={[{ required: true, message: "请输入任职要求" }]}>
							<Input.TextArea />
						</Form.Item>
						<Form.Item label="招聘人数" name="person" rules={[{ required: true, message: "请输入招聘人数" }]}>
							<Input type="number" />
						</Form.Item>
						<Form.Item
							label="专业技能的权"
							name="professionalSkillsRight"
							rules={[{ required: true, message: "请输入专业技能的权" }]}
						>
							<Input type="number" />
						</Form.Item>
						<Form.Item
							label="沟通能力的权"
							name="communicationSkillsRight"
							rules={[{ required: true, message: "请输入沟通能力的权" }]}
						>
							<Input type="number" />
						</Form.Item>
						<Form.Item
							label="团队协作的权"
							name="teamworkAbilityRight"
							rules={[{ required: true, message: "请输入团队协作的权" }]}
						>
							<Input type="number" />
						</Form.Item>
						{/* 只有其他岗位类型才显示内容字段 */}
						{(planType as number) === 3 && (
							<Form.Item label="内容" name="content">
								<Input />
							</Form.Item>
						)}
					</Form>
				</Modal>
			)}
			
			{/* 添加部门数据调试区域，只在开发环境显示 */}
			{isDevelopment && (
				<div style={{ marginTop: 20, padding: 10, border: '1px dashed #ccc' }}>
					{/* 调试信息 */}
				</div>
			)}
		</div>
	);
};

// 提供给其他组件使用的主要组件
export const DeptManageComponent: React.FC<DeptManagePageProps> = ({ 
	selectedPlanId: planId, 
	onCancel, 
	onSuccess 
}) => {
	// 使用props中的计划ID而不是从URL获取
	const [selectedPlanId, setSelectedPlanId] = useState<string>(planId || "");
	
	// 计划ID变化时更新状态
	useEffect(() => {
		if (planId) {
			setSelectedPlanId(planId);
		}
	}, [planId]);
	
	// 使用传入的回调函数，如果没有则使用默认函数
	const handleCancel = () => {
		if (onCancel) {
			onCancel();
		} else if (typeof window !== 'undefined') {
			window.history.back();
		}
	};
	
	const handleSuccess = () => {
		if (onSuccess) {
			onSuccess();
		} else if (typeof window !== 'undefined') {
			window.location.reload();
		}
	};
	
	return (
		<>
			{selectedPlanId ? (
				<DeptManageContent 
					selectedPlanId={selectedPlanId}
					onCancel={handleCancel}
					onSuccess={handleSuccess}
				/>
			) : (
				<div style={{ padding: "20px", textAlign: "center" }}>
					<Title level={3}>未找到招聘计划ID</Title>
					<Button onClick={handleCancel}>返回</Button>
				</div>
			)}
		</>
	);
};

// 默认导出组件以便于动态导入
export default DeptManageComponent; 